package com.findtech.threePomelos.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.FindCallback;
import com.findtech.threePomelos.R;
import com.findtech.threePomelos.base.MyActionBarActivity;
import com.findtech.threePomelos.base.MyApplication;
import com.findtech.threePomelos.bluetooth.AppManager;
import com.findtech.threePomelos.bluetooth.BLEDevice;
import com.findtech.threePomelos.bluetooth.CubicBLEDevice;
import com.findtech.threePomelos.database.OperateDBUtils;
import com.findtech.threePomelos.entity.BabyInfoEntity;
import com.findtech.threePomelos.entity.TravelInfoEntity;
import com.findtech.threePomelos.net.NetWorkRequest;
import com.findtech.threePomelos.utils.FileUtils;
import com.findtech.threePomelos.utils.MyCalendar;
import com.findtech.threePomelos.utils.PicOperator;
import com.findtech.threePomelos.utils.RequestUtils;
import com.findtech.threePomelos.login.ThirdPartyController;
import com.findtech.threePomelos.utils.ToastUtil;
import com.findtech.threePomelos.utils.Tools;
import com.findtech.threePomelos.view.dialog.CustomDialog;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

/**
 * Created by zhi.zhang on 2016/2/3.
 */
public class HomeActivity extends MyActionBarActivity implements View.OnClickListener,
        BLEDevice.RFStarBLEBroadcastReceiver, AppManager.RFStarManageListener {

    private TextView weightNum, heightNum, babyAge, babyName, totalMileage, todayMileage,
            averageSpeed, heightHealthState, weightHealthState, temperatureTv;
//    private Button noBindBtn;
    private ImageView mBabyInfoView;
    private boolean isBind, onceShow;
    private String deviceNum;
    private ThirdPartyController mThirdPartyController;
    private RelativeLayout heightLayout, weightLayout;
    private LinearLayout mileageLayout;
    private ImageView ImageViewMore;
    private ImageView ImageViewClose;
    private ImageView btnImageChoosePic;
    private RelativeLayout HomeMenuLayout;
    private RelativeLayout aboutBtn, deviceBtn;
    private Bitmap bitmap;
    private BabyInfoEntity babyInfoEntity = BabyInfoEntity.getInstance();
    private TravelInfoEntity travelInfoEntity = TravelInfoEntity.getInstance();
    private MyBroadcastReceiver mBroadcastReceiver;
    private String photoPath = null, tempPhotoPath, camera_path;
    private File mCurrentPhotoFile;
    PicOperator picOperator;
    private NetWorkRequest netWorkRequest;
    private OperateDBUtils operateDBUtils;
    private String babyTotalMonth, oldBabyTotalMonth, oldBabySex, nowBabySex;
    private String TAG = "HomeActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        MyApplication.getInstance().addActivity(this);
        setToolbar(getResources().getString(R.string.app_name), false);
        initView();
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(OperateDBUtils.QUERY_FINISH);
        intentFilter.addAction(RequestUtils.RECEIVE_TEMPERATURE_ELECTRIC_ACTION);
        registerReceiver(mBroadcastReceiver, intentFilter);
        getContentResolver().registerContentObserver(OperateDBUtils.TABLE_TRAVEL_URI, true, contentObserver);
        getContentResolver().registerContentObserver(OperateDBUtils.WEIGHT_URI, true, contentObserver);
        netWorkRequest = new NetWorkRequest(this);
        operateDBUtils = new OperateDBUtils(this);
        picOperator = new PicOperator(this);

        isBind = babyInfoEntity.getIsBind();
        deviceNum = babyInfoEntity.getBluetoothDeviceId();
        BluetoothManager manager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bleAdapter = manager.getAdapter();
        app.manager.isEnabled(this);
        if (bleAdapter != null && bleAdapter.isEnabled()) {
            bindBluetooth();
        }
    }

    void initView() {
        heightLayout = (RelativeLayout) findViewById(R.id.height_layout);
        weightLayout = (RelativeLayout) findViewById(R.id.weight_layout);
        mileageLayout = (LinearLayout) findViewById(R.id.mileage_layout);
        mBabyInfoView = (ImageView) findViewById(R.id.baby_image);
        btnImageChoosePic = (ImageView) findViewById(R.id.btn_image_choose_pic);
        weightNum = (TextView) findViewById(R.id.weight_num);
        heightNum = (TextView) findViewById(R.id.height_num);
        babyName = (TextView) findViewById(R.id.baby_name);
        babyAge = (TextView) findViewById(R.id.baby_age);
        totalMileage = (TextView) findViewById(R.id.total_mileage);
        todayMileage = (TextView) findViewById(R.id.today_mileage);
        averageSpeed = (TextView) findViewById(R.id.average_speed);
        heightHealthState = (TextView) findViewById(R.id.height_health_state);
        weightHealthState = (TextView) findViewById(R.id.weight_health_state);
        ImageViewMore = (ImageView) findViewById(R.id.btn_menu_more);
        ImageViewClose = (ImageView) findViewById(R.id.btn_menu_close);
        HomeMenuLayout = (RelativeLayout) findViewById(R.id.home_menu_layout);
        temperatureTv = (TextView) findViewById(R.id.temperature);

        HomeMenuLayout.setOnClickListener(this);
        heightLayout.setOnClickListener(this);
        weightLayout.setOnClickListener(this);
        mileageLayout.setOnClickListener(this);
        mBabyInfoView.setOnClickListener(this);
        btnImageChoosePic.setOnClickListener(this);

        totalMileage.setText(getResources().getString(R.string.xliff_total_mileage_num, travelInfoEntity.getTotalMileage()));
        todayMileage.setText(getResources().getString(R.string.xliff_today_mileage_num, travelInfoEntity.getTodayMileage()));
        averageSpeed.setText(getResources().getString(R.string.xliff_average_speed_num, travelInfoEntity.getAverageSpeed()));

        oldBabyTotalMonth = RequestUtils.getSharepreference(this).getString(RequestUtils.BABY_TOTAL_MONTH, "-1");
        oldBabySex = babyInfoEntity.getBabySex();
    }

    @Override
    protected void onStart() {
        super.onStart();
        onceShow = true;
    }

    @Override
    protected void onResume() {
        super.onResume();

        boolean isLogin = RequestUtils.getSharepreference(this)
                .getBoolean(RequestUtils.IS_LOGIN, false);
        if (isLogin) {
            if ("请输入宝宝性别".equals(babyInfoEntity.getBabySex()) ||
                    "请输入宝宝生日".equals(babyInfoEntity.getBirthday()) ||
                    "请输入宝宝籍贯".equals(babyInfoEntity.getBabyNative())) {
                RequestUtils.getSharepreferenceEditor(this)
                        .putBoolean(RequestUtils.IS_LOGIN, false).apply();
                gotoBabyInfoViewDialog();
            }
        }
        
        mThirdPartyController = new ThirdPartyController(this);
        Log.d("ZZ", "onResume  WEIGHT = " + RequestUtils.getSharepreference(this).getString(RequestUtils.WEIGHT, "- -"));
        updateView();
        bitmap = PicOperator.getIconFromData(this);
        if (bitmap != null) {
            mBabyInfoView.setImageBitmap(PicOperator.toRoundBitmap(bitmap));
        } else {
            mBabyInfoView.setImageResource(R.mipmap.homepage_headdata_bg_nor);
        }
        if ("宝宝昵称".equals(babyInfoEntity.getBabyName())) {
            babyName.setVisibility(View.GONE);
        } else {
            babyName.setVisibility(View.VISIBLE);
        }
        babyName.setText(babyInfoEntity.getBabyName());
        heightHealthState.setText(getResources().getString(R.string.xliff_height_health_state,
                RequestUtils.getSharepreference(this).getString(RequestUtils.HEIGHT_HEALTH_STATE, "0~0")));
        weightHealthState.setText(getResources().getString(R.string.xliff_weight_health_state,
                RequestUtils.getSharepreference(this).getString(RequestUtils.WEIGHT_HEALTH_STATE, "0~0")));
        if (babyInfoEntity.getBirthday() != null) {
            try {
                final String currentDate = Tools.getSystemTimeInChina("yyyy-MM-dd");
                String birthday = babyInfoEntity.getBirthday().replace("年", "-").replace("月", "-").replace("日", "");
                babyInfoEntity.setBabyTotalDay(this, birthday, "0");
                MyCalendar myCalendar = new MyCalendar(birthday, currentDate);
                Log.d("ZZZ", "myCalendar.getDate() = " + myCalendar.getDate());
                babyAge.setText(myCalendar.getDate());
                babyTotalMonth = myCalendar.getStandardDate();
                Log.d("ZZ", "oldBabyTotalMonth = " + oldBabyTotalMonth + " babyTotalMonth = " + babyTotalMonth);
                String heightHealthStateSp = RequestUtils.getSharepreference(this).getString(RequestUtils.HEIGHT_HEALTH_STATE, "0~0");
                String weightHealthStateSp = RequestUtils.getSharepreference(this).getString(RequestUtils.WEIGHT_HEALTH_STATE, "0~0");
                nowBabySex = babyInfoEntity.getBabySex();
                Log.d("ZZ", "oldBabySex = " + oldBabySex + " nowBabySex = " + nowBabySex);
                if (!oldBabyTotalMonth.equals(babyTotalMonth) ||
                        (oldBabySex != null && !oldBabySex.equals(nowBabySex))||
                        "0~0".equals(heightHealthStateSp) ||
                        "0~0".equals(weightHealthStateSp)) {
                    getHealthStateDataUpdateView(babyTotalMonth);
                    RequestUtils.getSharepreferenceEditor(this).putString(RequestUtils.BABY_TOTAL_MONTH, babyTotalMonth).commit();
                    if (oldBabySex != null && !oldBabySex.equals(nowBabySex)) {
                        oldBabySex = nowBabySex;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            RequestUtils.getSharepreferenceEditor(HomeActivity.this).putString(RequestUtils.HEIGHT_HEALTH_STATE, "0~0").commit();
            RequestUtils.getSharepreferenceEditor(HomeActivity.this).putString(RequestUtils.WEIGHT_HEALTH_STATE, "0~0").commit();
            heightHealthState.setText(getResources().getString(R.string.xliff_height_health_state, "0~0"));
            weightHealthState.setText(getResources().getString(R.string.xliff_weight_health_state, "0~0"));
        }
    }

    private void updateView() {
        weightNum.setText(getResources().getString(R.string.xliff_weight_num,
                RequestUtils.getSharepreference(this).getString(RequestUtils.WEIGHT, "- -")));
        heightNum.setText(getResources().getString(R.string.xliff_height_num,
                RequestUtils.getSharepreference(this).getString(RequestUtils.HEIGHT, "- -")));
        totalMileage.setText(getResources().getString(R.string.xliff_total_mileage_num, travelInfoEntity.getTotalMileage()));
        todayMileage.setText(getResources().getString(R.string.xliff_today_mileage_num, travelInfoEntity.getTodayMileage()));
        averageSpeed.setText(getResources().getString(R.string.xliff_average_speed_num, travelInfoEntity.getAverageSpeed()));
    }

    private void bindBluetooth() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Bundle bundle = getIntent().getExtras();
                boolean isSkip = false;
                if (bundle != null) {
                    isSkip = bundle.getBoolean("isSkip", false);
                }
                if (!isSkip && !TextUtils.isEmpty(deviceNum)) {//不是跳过，而且有蓝牙地址，就自动连接
                    app.manager.setRFstarBLEManagerListener(HomeActivity.this);
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                        app.manager.startScanBluetoothDevice();
                    } else {
                        startScanBluetoothDevice();
                    }
                }
//                if (app.manager.cubicBLEDevice != null)
//                    app.manager.cubicBLEDevice.setBLEBroadcastDelegate(HomeActivity.this);
            }
        }, 300);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MyApplication.getInstance().exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onReceive(Context context, Intent intent, String macData, String uuid) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onReceiveDataAvailable(String dataType, String data, TravelInfoEntity travelInfoEntity, String time) {
        Log.d("ZZ", "HomeActivity -> 有数据 save");
        if (RequestUtils.WEIGHT.equals(dataType)) {
            Log.d("ZZ", "HomeActivity -> 有数据 WEIGHT = " + data);
            RequestUtils.getSharepreferenceEditor(this).putString(RequestUtils.WEIGHT, data).commit();
            weightNum.setText(getResources().getString(R.string.xliff_weight_num, data));
            operateDBUtils.queryUserWeightData();
        }
        if (RequestUtils.TRAVEL_INFO.equals(dataType)) {
            if (travelInfoEntity != null) {
                totalMileage.setText(getResources().getString(R.string.xliff_total_mileage_num, travelInfoEntity.getTotalMileage()));
                todayMileage.setText(getResources().getString(R.string.xliff_today_mileage_num, travelInfoEntity.getTodayMileage()));
                averageSpeed.setText(getResources().getString(R.string.xliff_average_speed_num, travelInfoEntity.getAverageSpeed()));
            }
        }
        if (RequestUtils.TOTALE_MILEAGE.equals(dataType)) {
            totalMileage.setText(getResources().getString(R.string.xliff_total_mileage_num, data));
        }
    }

    @Override
    public void onClick(View view) {
        if (view == heightLayout) {
            Intent intent = new Intent(this, BabyDataDetailActivity.class);
            intent.putExtra("position", 0);
            startActivity(intent);
        }
        if (view == weightLayout) {
            Intent intent = new Intent(this, BabyDataDetailActivity.class);
            intent.putExtra("position", 1);
            startActivity(intent);
        }
        if (view == mileageLayout) {
            Intent intent = new Intent(this, BabyDataDetailActivity.class);
            intent.putExtra("position", 2);
            startActivity(intent);
        }
        if (view == mBabyInfoView) {
            startActivity(new Intent(this, BabyInfoActivity.class));
        }
        if (view == HomeMenuLayout) {
            showPopWindow();
        }
        if (view == aboutBtn) {
            startActivity(new Intent(this, AboutActivity.class));
            popupWindow.dismiss();
        }
        if (view == deviceBtn) {
            startActivity(new Intent(this, MyDeviceActivity.class));
            popupWindow.dismiss();
        }
        if (view == btnImageChoosePic) {
            PackageManager pm = getPackageManager();
            boolean permission = (PackageManager.PERMISSION_GRANTED ==
                    pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", this.getPackageName()));
            if (permission) {
                showPicChooserDialog();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void startScanBluetoothDevice() {
        int hasAccessCoarseLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
        int hasAccessFineLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);

        if (hasAccessCoarseLocationPermission != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_CODE_ASK_ACCESS_COARSE_LOCATION_PERMISSIONS);
            return;
        }
        if (hasAccessFineLocationPermission != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_CODE_ASK_ACCESS_FINE_LOCATION_PERMISSIONS);
            return;
        }
        app.manager.startScanBluetoothDevice();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_ACCESS_COARSE_LOCATION_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    app.manager.startScanBluetoothDevice();
                } else {
                    // Permission Denied
                    ToastUtil.showToast(this, "取消授权将无法搜索婴儿推车");
                }
                break;
            case REQUEST_CODE_ASK_ACCESS_FINE_LOCATION_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    app.manager.startScanBluetoothDevice();
                } else {
                    // Permission Denied
                    ToastUtil.showToast(this, "取消授权将无法搜索婴儿推车");
                }
                break;
            case WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showPicChooserDialog();
                } else {
                    ToastUtil.showToast(this, getResources().getString(R.string.text_toast_no_storage_permission));
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private Dialog mPicChooserDialog = null;

    private void showPicChooserDialog() {
        View viewDialog = getLayoutInflater().inflate(R.layout.dialog_pic_chooser, null);
        mPicChooserDialog = new Dialog(this, R.style.MyDialogStyleBottom);
        mPicChooserDialog.setContentView(viewDialog, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        DisplayMetrics dm = new DisplayMetrics();
        Window dialogWindow = mPicChooserDialog.getWindow();
        WindowManager m = dialogWindow.getWindowManager();
        m.getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams p = dialogWindow.getAttributes();
        p.width = dm.widthPixels;
        p.alpha = 1.0f;
        p.dimAmount = 0.6f;
        p.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(p);
        mPicChooserDialog.show();
        TextView btnCamera = (TextView) viewDialog.findViewById(R.id.btn_take_photo);
        TextView btnGallery = (TextView) viewDialog.findViewById(R.id.btn_pick_photo);
        TextView btnCancel = (TextView) viewDialog.findViewById(R.id.btn_cancel);
        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChoosePicFromCamera();
                mPicChooserDialog.dismiss();
            }
        });
        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChoosePicFromGallery();
                mPicChooserDialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicChooserDialog.dismiss();
            }
        });
    }

    private PopupWindow popupWindow = null;

    private void showPopWindow() {
        ImageViewMore.setVisibility(View.GONE);
        ImageViewClose.setVisibility(View.VISIBLE);
        final View mPopWindowView = getLayoutInflater().inflate(R.layout.pop_window_menu, null);
        popupWindow = new PopupWindow(mPopWindowView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        ColorDrawable cd = new ColorDrawable(0x000000);
        popupWindow.setBackgroundDrawable(cd);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
        popupWindow.showAsDropDown(ImageViewMore, 0, 26);
        popupWindow.update();
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            public void onDismiss() {
                popupWindow.dismiss();
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
                ImageViewMore.setVisibility(View.VISIBLE);
                ImageViewClose.setVisibility(View.GONE);
            }
        });
        aboutBtn = (RelativeLayout) mPopWindowView.findViewById(R.id.rl_about);
        deviceBtn = (RelativeLayout) mPopWindowView.findViewById(R.id.rl_device);
        aboutBtn.setOnClickListener(this);
        deviceBtn.setOnClickListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        app.manager.stopScanBluetoothDevice();
        unregisterReceiver(mBroadcastReceiver);
        getContentResolver().unregisterContentObserver(contentObserver);
    }

    @Override
    public void RFstarBLEManageListener(BluetoothDevice device, int rssi, byte[] scanRecord) {
        Log.d(MyApplication.TAG, "scanrecord : " + device.getAddress());// device.getName());
        if (!TextUtils.isEmpty(deviceNum) && deviceNum.equals(device.getAddress())) {
            app.manager.stopScanBluetoothDevice();
            app.manager.cubicBLEDevice = new CubicBLEDevice(getApplicationContext(), device);
            app.manager.cubicBLEDevice.setBLEBroadcastDelegate(HomeActivity.this);
        } else {
            Log.d(MyApplication.TAG, "RFstarBLEManageListener : " + device.getAddress());// device.getName());
        }
    }

    @Override
    public void RFstopBLEManageListener(BluetoothDevice device, int rssi, byte[] scanRecord) {

    }

    @Override
    public void RFstarBLEManageStartScan() {

    }

    @Override
    public void RFstarBLEManageStopScan() {

    }

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getExtras() != null) {
                if (intent.getAction().equals(OperateDBUtils.QUERY_FINISH)) {
                    String data = intent.getExtras().getString(OperateDBUtils.QUERY_DATA);
                    Log.d("ZZ", "MyBroadcastReceiver data = " + data);
                    onResume();
                }
                if (intent.getAction().equals(RequestUtils.RECEIVE_TEMPERATURE_ELECTRIC_ACTION)) {
                    String temperature = intent.getExtras().getString(RequestUtils.TEMPERATURE);
                    temperatureTv.setText(temperature + " ℃");
                    temperatureTv.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void ChoosePicFromCamera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File dir = new File(FileUtils.DCIMCamera_PATH );
        if (!dir.exists()) {
            boolean isCreate = dir.mkdir();
            Log.d(TAG, "no dir and create it :" + isCreate);
        }
        tempPhotoPath = FileUtils.DCIMCamera_PATH + "temp.jpg";
        mCurrentPhotoFile = new File(tempPhotoPath);
        if (mCurrentPhotoFile.exists()) {
            mCurrentPhotoFile.delete();
        }
        try {
            mCurrentPhotoFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(mCurrentPhotoFile));
        startActivityForResult(intent, Tools.CAMERA_WITH_DATA);
    }

    private void ChoosePicFromGallery() {
        Intent openphotoIntent = new Intent(Intent.ACTION_PICK);
        openphotoIntent.setType("image/*");
        startActivityForResult(openphotoIntent, Tools.PHOTO_PICKED_WITH_DATA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("ZZ", "requestCode = " + requestCode);
        Log.d("ZZ", "resultCode = " + resultCode);
        Log.d("ZZ", "data = " + data);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case AppManager.REQUEST_CODE:
                bindBluetooth();
                break;
            case Tools.CAMERA_WITH_DATA:
                photoPath = tempPhotoPath;
                camera_path = FileUtils.SaveBitmapToFilePath(picOperator.decodeBitmapFromFilePath(photoPath, 900, 900), FileUtils.SOURCE_IMAGE_FILEFOLDER_TEMP);
                startTagImageActivity();
                break;
            case Tools.PHOTO_PICKED_WITH_DATA:
                Uri originalUri = data.getData();
                photoPath = FileUtils.getPath(this, originalUri);
                camera_path = FileUtils.SaveBitmapToFilePath(picOperator.decodeBitmapFromFilePath(photoPath, 900, 900), FileUtils.SOURCE_IMAGE_FILEFOLDER_TEMP);
                startTagImageActivity();
                break;
            default:
                break;
        }
    }

    public void startTagImageActivity() {
        String babyDays = RequestUtils.getSharepreference(this).getString(RequestUtils.TOTALE_DAY, "0");
        String weight = getResources().getString(R.string.xliff_weight_num,
                RequestUtils.getSharepreference(this).getString(RequestUtils.WEIGHT, "- -"));
        String height = getResources().getString(R.string.xliff_height_num,
                RequestUtils.getSharepreference(this).getString(RequestUtils.HEIGHT, "- -"));
        Intent intent = new Intent(HomeActivity.this, TagImageEditActivity.class);
        intent.putExtra("camera_path", camera_path);
        intent.putExtra("baby_days", babyDays);
        intent.putExtra("baby_height", height);
        intent.putExtra("baby_weight", weight);
        HomeActivity.this.startActivity(intent);
    }

    String height, weight;
    private void getHealthStateDataUpdateView(String babyTotalMonth) {
        Log.d("ZZ", "getHealthStateDataUpdateView");
        netWorkRequest.getHealthStateDataFromServer(babyInfoEntity.getBabySex(), babyTotalMonth, new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list != null && list.size() > 0) {
                        for (AVObject avObject : list) {
                            height = avObject.getString(NetWorkRequest.HEIGHT_RANGE);
                            weight = avObject.getString(NetWorkRequest.WEIGHT_RANGE);
                        }
                        Log.d("ZZ", "getHealthStateDataUpdateView");
                    } else {
                        height = RequestUtils.getSharepreference(HomeActivity.this).getString(RequestUtils.HEIGHT_HEALTH_STATE, "0~0");
                        weight = RequestUtils.getSharepreference(HomeActivity.this).getString(RequestUtils.WEIGHT_HEALTH_STATE, "0~0");
                        Log.d("ZZ", "getHealthStateDataUpdateView2");
                    }
                } else {
                    height = RequestUtils.getSharepreference(HomeActivity.this).getString(RequestUtils.HEIGHT_HEALTH_STATE, "0~0");
                    weight = RequestUtils.getSharepreference(HomeActivity.this).getString(RequestUtils.WEIGHT_HEALTH_STATE, "0~0");
                    Log.d("ZZ", "getHealthStateDataUpdateView3");
                }
                handler.sendEmptyMessage(0x97);
            }
        });
    }

    /**
     *
     */
    private void gotoBabyInfoViewDialog() {
        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("提示");
        builder.setNotifyInfo("请输入宝贝的详细信息！");

        builder.setShowButton(true);
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startActivity(new Intent(HomeActivity.this, BabyInfoActivity.class));
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    ContentObserver contentObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            Log.d("ZZ", "ContentObserver uri = " + uri);
            if (uri.getPath().contains(OperateDBUtils.TABLE_TRAVEL_INFO)) {
                totalMileage.setText(getResources().getString(R.string.xliff_total_mileage_num, travelInfoEntity.getTotalMileage()));
                todayMileage.setText(getResources().getString(R.string.xliff_today_mileage_num, travelInfoEntity.getTodayMileage()));
                averageSpeed.setText(getResources().getString(R.string.xliff_average_speed_num, travelInfoEntity.getAverageSpeed()));
            }
            if (uri.getPath().contains(OperateDBUtils.WEIGHT)) {
//                RequestUtils.mUserWeightChangeListener.userWeightChange();
                Log.d("ZZ", "ContentObserver queryUserWeightData");
                operateDBUtils.queryUserWeightData();
//                String weight = RequestUtils.getSharepreference(HomeActivity.this).getString(RequestUtils.WEIGHT, );
//                weightNum.setText(getResources().getString(R.string.xliff_weight_num, weight));
            }
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x97) {
                RequestUtils.getSharepreferenceEditor(HomeActivity.this).putString(RequestUtils.HEIGHT_HEALTH_STATE, height).commit();
                RequestUtils.getSharepreferenceEditor(HomeActivity.this).putString(RequestUtils.WEIGHT_HEALTH_STATE, weight).commit();
                heightHealthState.setText(getResources().getString(R.string.xliff_height_health_state, height));
                weightHealthState.setText(getResources().getString(R.string.xliff_weight_health_state, weight));
            }
        }
    };
}